package com.aiapphub.SystemCode.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.aiapphub.SystemCode.entity.AppMapping;
import com.aiapphub.SystemCode.mapper.AppMappingMapper;
import com.aiapphub.SystemCode.service.AppMappingService;
import org.springframework.stereotype.Service;
import java.util.Date;
import java.util.List;

/**
 * App映射服务实现类
 */
@Service
public class AppMappingServiceImpl extends ServiceImpl<AppMappingMapper, AppMapping> implements AppMappingService {

    @Override
    public List<AppMapping> listAllMappings() {
        return baseMapper.selectList(new QueryWrapper<AppMapping>().orderByDesc("create_time"));
    }

    @Override
    public List<AppMapping> listEnabledMappings() {
        return baseMapper.selectList(new QueryWrapper<AppMapping>()
                .eq("status", 1)
                .orderByDesc("create_time"));
    }

    @Override
    public AppMapping getMappingByApiKey(String realApiKey) {
        return baseMapper.selectById(realApiKey);
    }

    @Override
    public AppMapping getByAppName(String appName) {
        QueryWrapper<AppMapping> wrapper = new QueryWrapper<>();
        wrapper.eq("app_name", appName)
               .eq("status", 1);
        return baseMapper.selectOne(wrapper);
    }

    @Override
    public boolean saveMapping(AppMapping mapping) {
        // 设置默认值
        if (mapping.getStatus() == null) {
            mapping.setStatus(1);
        }
        // 手动设置时间字段
        Date now = new Date();
        mapping.setCreateTime(now);
        mapping.setUpdateTime(now);
        return save(mapping);
    }

    @Override
    public boolean updateMapping(AppMapping mapping) {
        // 手动设置更新时间
        mapping.setUpdateTime(new Date());
        return updateById(mapping);
    }

    @Override
    public boolean deleteMapping(String realApiKey) {
        return removeById(realApiKey);
    }

    @Override
    public boolean updateStatus(String realApiKey, Integer status) {
        AppMapping mapping = new AppMapping();
        mapping.setRealApiKey(realApiKey);
        mapping.setStatus(status);
        return updateById(mapping);
    }
}

